﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
using U9API.Pub;
using System.Data;
using U9API.JsonModel;
using Newtonsoft.Json;
using System.Reflection;

namespace U9API.APIHelper
{

    public class SO
    {
        public Int64 ID { get; set; }
        public string DocNo { get; set; }
        public Int64 OrderBy_Customer { get; set; }
        public string DocumentType { get; set; }

        public int SOSrcType { get; set; }
        public Int64 BillToSite_CustomerSite { get; set; }
        public Int64 PayerSite_CustomerSite { get; set; }
        public string Cust_Memo { get; set; }
        public bool IsPriceIncludeTax { get; set; }
        public string TaxSchedule { get; set; }
        public string BusinessDate { get; set; }
        public int Status { get; set; }
        public string Cust_ShipToSiteLinker { get; set; }
        public Int64 ShipToSite_CustomerSite { get; set; }
        public Int64 Seller { get; set; }
        public List<SOLine> SOLines { get; set; }
         
        public Int64 SaleDepartment {get;set;}

        public string SellerCode { get; set; }
        public string SaleDepartmentCode { get; set; }
        public string SellerName { get; set; }
    }


    public class SOLine
    {
        public Int64 ID { get; set; }
        public string ItemInfo_ItemCode { get; set; }
        public Int64 ItemInfo_ItemID { get; set; }
        public string PasteItemCode { get; set; }
        public decimal OrderByQtyTU { get; set; }

        public string HS { get; set; }
        public string CasingNumber { get; set; }
        public decimal OrderPriceTC { get; set; }
        public decimal DiscountRate { get; set; }
        public decimal FinallyPriceTC { get; set; }
        public decimal TotalMoneyTC { get; set; }
        public decimal NetMoneyTC { get; set; }
        public decimal TaxMoneyTC { get; set; } 
        public string Memo { get; set; } 
        public string SrcDocNo { get; set; }
        public string PreDeliveryDate { get; set; }

        public bool lsPricelncludeTax { get; set; }
        public decimal SOLineSumInfo_SumShipQtyTU { get; set; }

        public string ItemInfo_ItemName { get; set; }
        public string SPECS { get; set; }
        public int Status { get; set; }
        public string PlanDate { get; set; }
    }



    public class SOQueryHelper : BaseHelper<JsonModel.ApiQuery>
    { 
        public List<U9API.DBHelper.Model.Customer> Resdatas { get; set; }
        public string result;


        private SO DataRowToHModel(DataRow row)
        {
            SO model = new SO();
            Type examType = typeof(SO);
            BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
            if (row != null)
            {
                DataColumnCollection dc = row.Table.Columns;
                for (int i = 0; i < dc.Count; i++)
                {
                    if (row[dc[i].ColumnName] != null && row[dc[i].ColumnName].ToString() != "")
                    {
                        PropertyInfo piInstance = examType.GetProperty(dc[i].ColumnName, flag);
                        if (piInstance != null)
                        {
                            piInstance.SetValue(model, row[dc[i].ColumnName], null);
                        }
                    }
                }
            }

            return model;
        }

        private SOLine DataRowToBModel(DataRow row)
        {
            SOLine model = new SOLine();

            Type examType = typeof(SOLine);
            BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
            if (row != null)
            {
                DataColumnCollection dc = row.Table.Columns;
                for (int i = 0; i < dc.Count; i++)
                {
                    if (row[dc[i].ColumnName] != null && row[dc[i].ColumnName].ToString() != "")
                    {
                        PropertyInfo piInstance = examType.GetProperty(dc[i].ColumnName, flag);
                        if (piInstance != null)
                        {
                            piInstance.SetValue(model, row[dc[i].ColumnName], null);
                        }
                    }
                }
            }
            return model;
        }



        protected override void Create(string U9constr, int operation, List<JsonModel.ApiQuery> models )
        {
            //Pub.WriteLog.WriteLine(DateTime.Now.ToShortDateString() + ": SOQueryHelper");
            if (models.Count == 0)
            {
                throw new Exception("查询条件不允许为空!");
            }
            JsonModel.ApiQuery model = models[0];
            StringBuilder sql = new StringBuilder();
            sql.Append(" select A7.Code as SellerCode, A8.Code as SaleDepartmentCode,   A.Seller, A.SaleDepartment, A.ID, DocNo, OrderBy_Customer, A1.Code as DocumentType, SOSrcType, BillToSite_CustomerSite, PayerSite_CustomerSite, A3.Description as Cust_Memo, IsPriceIncludeTax, A4.Code as TaxSchedule,Convert(varchar(10), BusinessDate,121) as  BusinessDate, Status, A5.LinkMan_Name as Cust_ShipToSiteLinker, ShipToSite_CustomerSite, A6.Name as SellerName ");
            sql.Append(" from SM_SO A");
            sql.Append(" LEFT JOIN SM_SODocType A1 ON A1.ID = A.DocumentType ");
            sql.Append(" LEFT JOIN SM_SOMemo A2 ON A2.SO = A.ID");
            sql.Append(" LEFT JOIN SM_SOMemo_Trl A3 ON A3.ID = A2.ID");
            sql.Append(" left join CBO_TaxSchedule A4 ON A4.ID = A.TaxSchedule");
            sql.Append(" LEFT JOIN SM_SOContact A5 on A5.SO = A.ID AND A5.LinkMan_OwnerType = 0 ");
            sql.Append(" LEFT JOIN CBO_Operators_Trl A6 on A6.ID = A.Seller ");
            sql.Append(" LEFT JOIN CBO_Operators A7 ON A7.ID = A.Seller ");
            sql.Append(" LEFT JOIN CBO_Department A8 on A8.ID = A.SaleDepartment ");
            sql.Append(" WHERE 1=1 ");


            if (!string.IsNullOrEmpty(model.code))
            {
                sql.Append("and A.DocNo = '" + model.code + "'");
            }
            if (!string.IsNullOrEmpty(model.id))
            {
                sql.Append("and A.ID = '" + model.id + "'");
            }
            if (!string.IsNullOrEmpty(model.customer))
            {
                sql.Append("and A.OrderBy_Customer = '" + model.customer + "'");
            }
            if (!string.IsNullOrEmpty(model.startdate))
            {
                sql.Append(" and (A.CreatedOn >='" + model.startdate + "' or A.ModifiedOn >='" + model.startdate +"')");
            }
            if (!string.IsNullOrEmpty(model.enddate))
            {
                sql.Append(" and (A.CreatedOn <='" + model.enddate + "' or A.ModifiedOn <='" + model.enddate + "')");
            }
            DataSet ds = DbHelperSQL.Query(sql.ToString(), U9constr);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                List<SO> mlist = new List<SO>();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    mlist.Add(DataRowToHModel(ds.Tables[0].Rows[i]));
                }
                
                foreach (var item in mlist)
                {
                    StringBuilder sqlb = new StringBuilder();
                    sqlb.Append(" SELECT A.ItemInfo_ItemName, A1.SPECS, A.Status,Convert(varchar(10), A5.PlanDate,121) as PlanDate, A.ID, A.ItemInfo_ItemCode, A.ItemInfo_ItemID, A.PasteItemCode, OrderByQtyTU,A1.DescFlexField_PrivateDescSeg1 as HS, A1.DescFlexField_PubDescSeg10 as  CasingNumber, OrderPriceTC, A.DiscountRate, A.FinallyPriceTC, A.NetMoneyTC, TaxMoneyTC, Convert(varchar(10), a4.RequireDate, 121) as PreDeliveryDate, A.DescFlexField_PrivateDescSeg3 AS Memo, A.TotalMoneyTC, A.SrcDocNo, A.OriginalPriceIncludeTax as lsPricelncludeTax, A.SOLineSumInfo_SumShipQtyTU ");
                    sqlb.Append(" FROM  SM_SOLine A  ");
                    sqlb.Append(" LEFT JOIN CBO_ItemMaster A1 ON A1.ID = A.ItemInfo_ItemID ");
                    sqlb.Append(" LEFT JOIN SM_SOShipline A4 ON A4.SOLine = A.ID ");
                    sqlb.Append(" LEFT JOIN SM_SOShipline A5 ON A5.SOLine = A.ID ");
                    sqlb.Append(" WHERE A.SO = '" + item.ID + "' ");
                    //Pub.WriteLog.WriteLine(sql.ToString());

                    DataTable dtb = DbHelperSQL.QueryAsDT(sqlb.ToString(), U9constr);
                    if (dtb != null && dtb.Rows.Count > 0)
                    {
                        item.SOLines = new List<SOLine>();
                        for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            item.SOLines.Add(DataRowToBModel(dtb.Rows[i]));
                        }
                    }
                }
                result = mlist.ToJson(); 
            }
            else
            {
                throw new Exception("没有查到匹配的销售订单记录!");
                
            }
        }
         
    }
}
